package com.originskyseed.platform.user.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Player;
import com.originskyseed.platform.user.model.PlayerRelateRewardApply;
import com.originskyseed.platform.user.model.TradeUnion;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IPlayerRelateRewardApplyService;
import com.originskyseed.platform.user.service.IPlayerRelateRewardReviewService;
import com.originskyseed.platform.user.service.IPlayerService;
import com.originskyseed.platform.user.service.ITradeUnionService;
import com.originskyseed.platform.user.vo.request.PlayerRelateRewardApplyRequestVO;

/**
 * 玩家奖励申请表Controller类（OSI_PLAYER_RELATE_REWARD_APPLY）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/playerRelateRewardApply")
@BaseLocaleResource(localeFileName = "i18n_user")
public class PlayerRelateRewardApplyController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PlayerRelateRewardApplyController.class);

	@DubboReference
	private IPlayerRelateRewardApplyService playerRelateRewardApplyService;

	@DubboReference
	private IPlayerRelateRewardReviewService playerRelateRewardReviewService;

	@DubboReference
	private IPlayerService playerService;

	@DubboReference
	private ITradeUnionService tradeUnionService;

	/**
	 * 奖励申请记录_分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardApplyList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PlayerRelateRewardApply>> playerRelateRewardApplyList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PlayerRelateRewardApply>> result = null;
		try {
			// 请求对象
			PlayerRelateRewardApplyRequestVO requestVO = this.getParameterBean(PlayerRelateRewardApplyRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// if(userInfo.getSourceSys() == 2 && (userInfo.getType() == 2 || userInfo.getType() == 3 || userInfo.getType() == 4 || userInfo.getType() == 5))
			{
				/*
				 * TradeUnion tradeUnion = this.tradeUnionService.selectByUserId(userInfo.getId()); requestVO.setTradeUnionId(tradeUnion.getId());
				 */
				// 分页查询
				BasePage<PlayerRelateRewardApply> page = new BasePage<PlayerRelateRewardApply>(requestVO.getPageNo(), requestVO.getPageSize());
				page = this.playerRelateRewardApplyService.selectListByPage(requestVO.toMap(), page);
				result = new BaseResponseBody<BasePage<PlayerRelateRewardApply>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PlayerRelateRewardApply>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 奖励申请发放查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPlayerRelateRewardApplyByPlayerId.json")
	@RequiredParams(names = { "playerId" })
	public BaseResponseBody selectPlayerRelateRewardApplyByPlayerId(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String playId = this.getParameterString("playerId", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (userInfo == null || userInfo.getOtherAccount() == null) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_OTHER_ACCONUT_ISNULL.getMsg()), null);
			}
			PlayerRelateRewardApply playerRelateRewardApply = new PlayerRelateRewardApply();
			// 请求接口
			TreeMap<String, Object> paramMap = new TreeMap<>();
			paramMap.put("playId", playId);
			paramMap.put("channelId", userInfo.getOtherAccount());
			Map resultMap = QueryAppUtil.query("playerAwardQueryUrl", 1, paramMap);
			Integer code = Integer.parseInt(resultMap.get("code").toString());
			String msg = (String) resultMap.get("msg");
			if (code == 1) {
				// json字符串转jsonArray
				String data = (String) resultMap.get("data");
				playerRelateRewardApply = JsonUtils.parse(data, PlayerRelateRewardApply.class);
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.RESULT_DATA_SUCCESS.getMsg()), playerRelateRewardApply);
			} else {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), msg, null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.REQUEST_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 奖励申请记录导出Excel模板
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@GetMapping("/playerRelateRewardApplyToExcelModel.json")
	@SysLog(module = "直播管理类模块", operationDesc = "奖励申请记录导出Excel模板")
	public void playerRelateRewardApplyToExcelModel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// excel标题
			String[] title = { "用户ID*", "奖励类型*", "申请时间*", "备注信息*", "操作人*", "所属子渠道*", "所属子渠道账号*" };
			// excel文件名
			String fileName = "奖励申请记录导出模板.xls";
			// sheet名
			String sheetName = "奖励申请记录导出模板";
			String[][] values = new String[0][];
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 奖励发放申请记录导出
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/playerRelateRewardApplyToExcel.json")
	@SysLog(module = "直播管理类模块", operationDesc = "奖励申请记录导出Excel")
	public void playerRelateRewardApplyToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			PlayerRelateRewardApplyRequestVO requestVO = this.getParameterBean(PlayerRelateRewardApplyRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			SimpleDateFormat RechargeTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<PlayerRelateRewardApply> list = null;
			if (userInfo.getSourceSys() == 2 && (userInfo.getType() == 2 || userInfo.getType() == 3 || userInfo.getType() == 4 || userInfo.getType() == 5)) {
				TradeUnion tradeUnion = this.tradeUnionService.selectByUserId(userInfo.getId());
				requestVO.setTradeUnionId(tradeUnion.getId());
				list = this.playerRelateRewardApplyService.selectPlayerRelateRewardApplyListToExcel(requestVO.toMap());
			}

			// excel标题
			String[] title = { "用户ID", "奖励类型", "申请时间", "备注信息", "操作人", "所属子渠道", "所属子渠道账号" };
			// excel文件名
			String fileName = "奖励申请记录信息.xls";
			// sheet名
			String sheetName = "奖励申请记录信息";
			String[][] values = new String[list.size()][];

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					PlayerRelateRewardApply obj = list.get(i);
					values[i][0] = obj.getPlayerId();
					if (obj.getType() != null) {
						if (obj.getType() == 1) {
							values[i][1] = "充值累积奖励";
						}
						if (obj.getType() == 2) {
							values[i][1] = "开通贵族奖励";
						}
						if (obj.getType() == 3) {
							values[i][1] = "登录奖励";
						}
					} else {
						values[i][1] = "";
					}
					values[i][2] = RechargeTime.format(obj.getApplyTime());
					values[i][3] = obj.getRemark() == null ? "" : obj.getRemark();
					values[i][4] = obj.getCreator();
					values[i][5] = obj.getChannelSubName() == null ? "" : obj.getChannelSubName();
					values[i][6] = obj.getChannelSubAccount() == null ? "" : obj.getChannelSubAccount();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 保存信息_奖励申请
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardApplySave.json")
	@RequiredParams(names = {})
	public BaseResponseBody playerRelateRewardApplySave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			PlayerRelateRewardApply playerRelateRewardApply = this.getParameterBean(PlayerRelateRewardApply.class);
			Player player = this.getParameterBean(Player.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (userInfo == null || userInfo.getOtherAccount() == null) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_OTHER_ACCONUT_ISNULL.getMsg()), null);
			}
			if (playerRelateRewardApply == null || playerRelateRewardApply.getPlayerId() == null) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PLAYER_ID_ISNULL.getMsg()), null);
			}

			if (StringUtils.isNotEmpty(player.getPlayerId())) {
				// 接口请求
				TreeMap<String, Object> paramMap = new TreeMap<>();
				paramMap.put("playId", playerRelateRewardApply.getPlayerId());
				paramMap.put("channelId", userInfo.getOtherAccount());
				paramMap.put("awardType", playerRelateRewardApply.getType());
				paramMap.put("awardRule", playerRelateRewardApply.getAwardRule());
				paramMap.put("awardPrizeId", playerRelateRewardApply.getAwardPrizeId());
				paramMap.put("sendVip", playerRelateRewardApply.getSendVip());
				// System.out.println("=playerRelateRewardApply=paramMap==" + paramMap);
				Map map = QueryAppUtil.query("playerAwardSubmitUrl", 2, paramMap);
				Integer code = Integer.parseInt(map.get("code").toString());
				String msg = (String) map.get("msg");
				// System.out.println("=playerRelateRewardApply=map==" + map);
				if (code == 1) {

					Player tempPlayer = playerService.selectByPlayerId(player.getPlayerId());
					String primaryKey = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
					playerRelateRewardApply.setId(primaryKey);
					playerRelateRewardApply.setNickName(tempPlayer == null ? "" : tempPlayer.getNickName());
					playerRelateRewardApply.setPlayerId(player.getPlayerId());
					playerRelateRewardApply.setApplyId(userInfo.getId());
					playerRelateRewardApply.setApplyName(userInfo.getName());
					playerRelateRewardApply.setCreatorId(userInfo.getId());
					playerRelateRewardApply.setCreator(userInfo.getName());
					playerRelateRewardApply.setChannelId(tempPlayer == null ? "" : tempPlayer.getChannelId());
					playerRelateRewardApply.setChannelSubId(tempPlayer == null ? "" : tempPlayer.getChannelSubId());
					playerRelateRewardApply.setApplyTime(new Date());
					this.playerRelateRewardApplyService.insertSelective(playerRelateRewardApply);

					result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.REQUEST_DATA_SUCCESS.getMsg()), true);
				} else {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), msg, null);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 公会下玩家信息查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPlayerInTradeUnion.json")
	@RequiredParams(names = { "id" })
	public BaseResponseBody<Player> selectPlayerInTradeUnion(HttpServletRequest request) {
		BaseResponseBody<Player> result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Player playerInfo = null;
			if (userInfo.getSourceSys() == 2 && (userInfo.getType() == 2 || userInfo.getType() == 3 || userInfo.getType() == 4 || userInfo.getType() == 5)) { // 会长、副会长
				if (StringUtils.isNotEmpty(id)) {
					TradeUnion tradeUnion = this.tradeUnionService.selectByUserId(userInfo.getId());
					Player player = new Player();
					player.setUserId(id);
					player.setTradeUnionId(tradeUnion.getId());
					playerInfo = this.playerService.selectPlayerByPlayer(player);
				}
			}
			result = new BaseResponseBody<Player>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PLAYER_DATA_EXIST.getMsg()), playerInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Player>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PLAYER_DATA_NOEXIST.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateRewardApplyDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> playerRelateRewardApplyDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.playerRelateRewardApplyService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}
